package com.phc.a20200511work.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * 版权：没有版权 看得上就用
 *
 * @author peng
 * 创建日期：2020/5/13 09
 * 描述：该工具类用于申请权限
 */
public class AccessRequestUtil  {
    private static final String TAG = "AccessRequestUtil";
    //常量用于表示请求的代码//日历，相机，联系人，位置，录音，手机，传感器，短信，存储
    public static final int CODE_READ_CALENDAR = 0;
    public static final int CODE_CAMERA = 1;
    public static final int CODE_CONTACTS = 2;
    public static final int CODE_LOCATION = 3;
    public static final int CODE_RECORD_AUDIO = 4;
    public static final int CODE_PHONE = 5;
    public static final int CODE_SENSORS = 6;
    public static final int CODE_SMS = 7;
    public static final int CODE_STORAGE = 8;
    //权限名称定义
    public static final String PERMISSION_READ_CALENDAR = Manifest.permission.READ_CALENDAR;
    public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    public static final String PERMISSION_CONTACTS = Manifest.permission.READ_CONTACTS;
    public static final String PERMISSION_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    public static final String PERMISSION_RECORD_AUDIO = Manifest.permission.RECORD_AUDIO;
    public static final String PERMISSION_PHONE = Manifest.permission.CALL_PHONE;
    public static final String PERMISSION_SENSORS = Manifest.permission.BODY_SENSORS;
    public static final String PERMISSION_SMS = Manifest.permission.READ_SMS;
    public static final String PERMISSION_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    //使用数组存储权限名称，写入时已经于请求代码保持了同步|
    static final String [] requestPermissions ={PERMISSION_READ_CALENDAR,PERMISSION_CAMERA,PERMISSION_CONTACTS,
    PERMISSION_LOCATION,PERMISSION_RECORD_AUDIO,PERMISSION_PHONE,PERMISSION_SENSORS,
    PERMISSION_SMS,PERMISSION_STORAGE};
    //定义一个接口表示请求成功
    public interface PermissionGrant{
        public void onPermissionGranted (int requestCode);
    }
    //该函数请求权限
    public static void requestPermission(Activity activity , int requestCode,PermissionGrant permissionGrant){
        if (activity == null){
            return;
        }
        //去除不存在的请求码
        if (requestCode<0 ||requestCode >= requestPermissions.length){
            return;
        }
        //得到需要请求的是哪一个权限
        String requestPermission = requestPermissions[requestCode];

        //判断手机版本号是否为6.0,6.0以下无需申请
        if (Build.VERSION.SDK_INT< 23){
            return;
        }

        //判断是否有授权，
        int checkSelfPermission = ActivityCompat.checkSelfPermission(activity,requestPermission);
        //如果已经被授权
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED){
            permissionGrant.onPermissionGranted(requestCode);
            Log.i(TAG, "requestPermission: 已经拥有用户权限");
        }else {
//            莫得权限，需要申请，
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity,requestPermission)){
                shouldShowRationale(activity,requestCode,requestPermission);
            }else {
                ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);
            }
        }
    }

    //申请授权结果的方法
    public static void requestPermissionsResult(Activity activity, int requestCode
            , @NonNull String[] permissions, @NonNull int[] grantResults
            , PermissionGrant permissionGrant){
        if (activity == null) {
            return;
        }
//        过滤无效请求码
        if(requestCode<0||requestCode>=requestPermissions.length){
            Toast.makeText(activity,"无效请求码："+requestCode,Toast.LENGTH_SHORT).show();
            return;
        }
        if (grantResults.length ==1&&grantResults[0]== PackageManager.PERMISSION_GRANTED) {
//            授权成功了
            permissionGrant.onPermissionGranted(requestCode);
        }else {
            String permissionError = requestPermissions[requestCode];
//            需要让用户打开设置自动去设置权限
            openSettingActivity(activity,"those permession need granted");
        }
    }

    private static void openSettingActivity(final Activity activity, String msg) {
        showMessageOKCancel(activity, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                打开设置界面
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package",activity.getPackageName(),null);
                intent.setData(uri);
                activity.startActivity(intent);
            }
        });
    }

    public static void shouldShowRationale(final Activity activity, final int requestCode, final String requestPermission){
        showMessageOKCancel(activity, "是否弹出" + requestPermission + "权限的申请", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions(activity,new String[]{requestPermission},requestCode);
            }
        });
    }
    /* 将弹出对话框的过程封装*/
    public static void showMessageOKCancel(Activity activity,String msg,DialogInterface.OnClickListener oklistener){
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("提示信息:").setMessage(msg)
                .setPositiveButton("OK", oklistener);
        builder.setNegativeButton("Cancel",null);
        builder.create().show();
    }

}
